import timeit,os,threading,multiprocessing
from utils import FileUtil,ExcelUtil,SettingUtil,PBGenUtil

class ExportExcelWorker:
    def __init__(self,callBack=None,useWorker=True) -> None:
        self.excelFiles = []
        self.oldTables = []
        self.oldChangeSets = None
        self.changeNum = 0
        self.totalCount = 0
        self.curCount = 0
        self.callBack = callBack
        self.isUseWorker = useWorker
        self.totalSheetInfos = []
    
    def readSheetInfos(self,excels:list)->list:
        totalTheads = []
        count = len(excels)
        self.totalCount = count
        for i in range(count):
            f = excels[i]
            if self.isUseWorker:
                t = threading.Thread(target=self._readSheetWorker,args=[f])
                # t = multiprocessing.Process(target=self._readSheetWorker,args=[f,lock])
                t.start()
                totalTheads.append(t)
            else:
                self.totalSheetInfos.extend(ExcelUtil.excelToSheetInfos(f))
            print("开始读取 f=",f)
            
        if not self.isUseWorker or count ==0:
            self.onWorkerEnd(self.totalSheetInfos)
    
    def _readSheetWorker(self,f):
        self.totalSheetInfos.extend(ExcelUtil.excelToSheetInfos(f))
        self.curCount += 1
        print("_readSheetWorker f=",f,"self.curCount=",self.curCount,"self.totalCount=",self.totalCount,"totalLen=",len(self.totalSheetInfos))
        if self.curCount >= self.totalCount:
            print("**********所有进程完成 总的配置数=",len(self.totalSheetInfos))
            self.onWorkerEnd(self.totalSheetInfos)
    
    def writeExcelToPB(self,root:str):
        print(f"开始读取[{root}]的所有excel表格..")
        oldTableMap = FileUtil.readConfigTableMap()
        excelFiles = []
        oldTables = []
        FileUtil.listRootExcels(root,excelFiles,oldTables,oldTableMap)
        oldChangeSets = set(oldTables)
        self.oldChangeSets = oldChangeSets
        self.readSheetInfos(excelFiles)
        
    def onWorkerEnd(self,sheetInfoArr):
        print("开始查询可能修改的表格并且生成数据 总配置数=",len(sheetInfoArr))
        changeSheetInfos,newTableSetToWrite,protoContent = ExcelUtil.filterConfig(sheetInfoArr)
        newTabeSetToFind = set([item.split("=")[0] for item in newTableSetToWrite]) #修改或新增
        oldChangeSets = self.oldChangeSets
        delSet,addSet =ExcelUtil.calChangeSet(oldChangeSets,newTabeSetToFind,newTableSetToWrite)
        if SettingUtil.getSetting().usePB:
            protoContent = ExcelUtil.removeMessage(protoContent,delSet)
            PBGenUtil.writeAndCompilePB(protoContent)
        st = timeit.default_timer()
        ExcelUtil.writeSheetToPB(changeSheetInfos)

        self.changeNum = len(changeSheetInfos)

        et = timeit.default_timer()
        costSec = et-st
        print(f"可能被修改的表格总数={self.changeNum} costSec=",costSec)
        FileUtil.writeConfigTableSet(newTableSetToWrite)
        extName = SettingUtil.getSetting().dataExt
        for pbFile in delSet:
            url = os.path.join(SettingUtil.getSetting().sheetPbRoot,pbFile+extName)
            if os.path.exists(url):
                print("**删除差集中的配置 url=",url)
                os.remove(url)
                
        print(f"**!!本次操作被删除的表!!**,delSet={delSet}")
        print(f"本次操作新增的表,addSet={addSet}")
        print(f"本次操作变化的表,{newTabeSetToFind}")
        if self.callBack !=None:
            self.callBack(self.changeNum)
        